<template>
<view>
	<u-navbar :is-back="false" title="进货下单"
	  title-size="30"
	  :background="{background:'#2B88FE' }"
	  title-color="#fff">
	  <div class="head_icon">
	    <u-icon @click="$api.handleBackTo"
	      name="arrow-left" color="#fff"
	      size="36">
	    </u-icon>
	    <u-icon @click="$api.handleHomeTo"
	      name="home" color="#fff" size="36">
	    </u-icon>
	  </div>
	</u-navbar>

  <view class="app-product">
    <block>
      <view class="topheader ">
        <view @click="personSelect" class="x-row">
          <view style="color:#f00" class="x-col-center">*</view>
          <view class="titel x-col">销售人员</view>
          <view class="rightimg x-col-center">
            <image :src="$api.UserImg(u.fId)" v-for="(u,index) in userLi" :key="index"
              class="img60"></image>
          </view>
          <u-icon name="arrow-right" color="#979797" size="26rpx"></u-icon>
        </view>
      </view>

      <view class="topheader x-row" style="border: 0;display: none;">
        <view class="titel x-col">订单凭证</view>
        <view class="upimg x-col-center" @click="imgshow">
          <view class="addBtn">{{simgs.length>0?simgs.length+'张图片':'请拍照/上传图片'}}</view>
        </view>
        <u-icon name="arrow-right" color="#979797" size="26rpx" class="x-col-center"></u-icon>
      </view>
      <view class="x-row" style="padding: 25upx 0;border-top: 1px solid #e5e5e5;"
        @click="selectGood">
        <!-- @click="add_ontime" -->
        <view class="x-col"></view>
        <image src="../../static/addicon.png" class="imgadd x-col-center"></image>
        <view class="bu_text x-col-center">添加进货产品</view>
        <view class="x-col"></view>
      </view>
      <view v-for="(item,index) in formdata" :key="index" class="product-list">
        <view class="nametext">进货产品{{indexshow-index}}
          <text class="fr" @click="delsdit(index)">删除</text>
        </view>
        <u-form label-width="150rpx" class="u-form">
          <u-form-item label="产品名称">{{item.gname}}</u-form-item>
		  <u-form-item label="产品规格">
		    <picker @change="confirmPrice($event,item)" :range="item.PriceList" range-key="fUnit">
		      {{item.ProUnitName}}
		      <u-icon style="margin-left:10rpx" name="arrow-down-fill" color="#666" size="20">
		      </u-icon>
		    </picker>
		  </u-form-item>
          <u-form-item label="单价"><input v-model="item.fSallPrice" /></u-form-item>
          <u-form-item label="销售方式">
            <picker @change="confirm($event,item)" :range="priceTypes" range-key="label">
              {{priceTypes[item.fType].label}}
              <u-icon style="margin-left:10rpx" name="arrow-down-fill" color="#666" size="20">
              </u-icon>
            </picker>
          </u-form-item>
          <u-form-item label="购买"  v-if="item.fType==0"><input v-model="item.fCount" /></u-form-item>
		  <u-form-item label="盖子" v-if="item.fType==0"><input v-model="item.fCoverCount" /></u-form-item>
		  <u-form-item label="搭赠" v-if="item.fType==0 || item.fType==1"><input v-model="item.fGiveCount" /></u-form-item>
		  <u-form-item label="换货" v-if="item.fType==0 || item.fType==2"><input v-model="item.fExcCount" /></u-form-item>
		  <u-form-item label="退货" v-if="item.fType==0 || item.fType==3"><input v-model="item.fRetCount"  @input="ReSetNow(g)" /></u-form-item>
          <u-form-item label="备注"><input type="textarea" v-model="item.fInfo" placeholder="请填写备注" />
          </u-form-item>
          <u-form-item label="价格合计"> <text>￥</text>{{showTotal(item)}}
          </u-form-item>
        </u-form>
      </view>
      <view class="btn-footer">
        <u-button class="btn1" type="success" @click="dialog=true">预览</u-button>
        <u-button class="btn2" type="primary" @click="Submit">（总价¥ {{Alltotal()}}）提交</u-button>
      </view>
      <u-modal v-model="dialog" title="商品信息" width="90%" confirm-text="关闭">
        <view class="slot-content">
          <u-table>
            <u-tr class="u-tr">
              <u-th class="u-th" width="30%">商品名称</u-th>
              <u-th class="u-th" width="15%">单位</u-th>
              <u-th class="u-th" width="15%">数量</u-th>
              <u-th class="u-th">单价</u-th>
              <u-th class="u-th">金额</u-th>
            </u-tr>
            <u-tr class="u-tr" v-for="(item,index) in formdata" :key="index">
              <u-td class="u-td" width="30%">{{item.gname}}</u-td>
              <u-td class="u-td" width="15%">{{item.fUnit}}</u-td>
              <u-td class="u-td" width="15%">{{item.fCount}}</u-td>
              <u-td class="u-td">{{item.fSallPrice}}</u-td>
              <u-td class="u-td"> {{showTotal(item)}}</u-td>
            </u-tr>
          </u-table>
        </view>
      </u-modal>
    </block>

  </view>
  </view>	
</template>

<script>
export default {
  data() {
    return {
      dialog: false,
      priceTypes: [
        {
          label: '正常销售',
          value: 0
        },
        {
          label: '免费赠品',
          value: 1
        },	 
		{
		  label: '换货',
		  value: 2
		} ,
		{
		  label: '退货',
		  value: 3
		} 
      ],
	  ProUnitName:'',
      form: {
        TaskId: 0,
        VisitId: 0,
        MrkId: 0,
        MrkName: '',
        Tell: '',
        Address: '',
        OrderType: 1, /// 订单类型 1进货订单 2兑换订单
        PriceType: 0, /// 价格类型 价格类型  0正常价  1折扣价  2VIP
        Pic: '',
        fMoney: 0,
        Info: '',
		prolist:[]
      },
	  clineOnce:true,
      action: '',
	  total:0,
      current: 0,
      index: 0, // 所有下拉选择公用下标
      formdata: [],
      list: [
        {
          name: '正常价'
        },
        {
          name: '折扣价'
        },
        {
          name: 'VIP价'
        }
      ],
      action: -1, //选择的商品下标
      oldid: '',
      id: '',
      bid: '',
      userLi: [],
      simgs: [],
      info: '',
      source: '' //来源 detail  详情 只展示数据 sj 司机添加商品直接提交订单
    }
  },
  onLoad(e) {
    if (e.fId) {
      this.form.VisitId = Number(e.fId)
    }
    if (e.fTaskId) {
      this.form.TaskId = Number(e.fTaskId)
    }
    this.$axios('api/MrkBasic/GetDetail', 'post', { value: e.fId }).then(res => {
      let info = res.Value
      this.form.MrkId = info.fId
      this.form.MrkName = info.fName
      this.form.Tell = info.fTell
      this.form.Address = info.fAddress

    })

    this.getClist()
  },
  onShow() {
    if (getApp().globalData.addCusGoodLi) {
      let orders = getApp().globalData.addCusGoodLi
      orders.forEach(x => {
        x.fCount = 1
		x.fCoverCount = 0
		x.fGiveCount = 0
		x.fExcCount = 0
		x.fRetCount = 0
        x.fType = 0
        x.show = false
        x.ProUnitName=x.fDefUnit
		x.fSallPrice=x.fDefPrice
      })
      this.formdata = orders
    }
    if (getApp().globalData.selectUserli) {
      this.userLi = getApp().globalData.selectUserli
    }
    if (getApp().globalData.sureSelectImg) {
      this.simgs = getApp().globalData.sureSelectImg
    }
  },

  //计算属性
  computed: {
    indexshow() {
      return parseInt(this.formdata.length)
    }
  },
  methods: {
    Alltotal() {
		
      this.total= this.formdata.reduce((v, m) => {
        if (m.fType ==0 ) {
           v += m.fCount * m.fSallPrice
		   v += -(m.fRetCount * m.fSallPrice)
		   }
		else if (m.fType ==3 ) {
		   v += -(m.fRetCount * m.fSallPrice)
        } else {
           v += 0 
        }
        return v
      }, 0)
	  return  this.total
    },
    showTotal(item) {
      if (item.fType == 1 || item.fType == 2) return 0
      return ((item.fCount * item.fSallPrice)-(item.fRetCount * item.fSallPrice)).toFixed(2)
    },
    confirm(e, item) {
      item.fType = e.detail.value
	  if(item.fType!=0)
	  {
		  item.fCount=0
	  }
      this.$forceUpdate()
    },
	ReSetNow(item){
	 //  item.fMoney=((item.fCount * item.fSallPrice)-(item.fRetCount * item.fSallPrice)).toFixed(2)
	   this.$forceUpdate()
	},
	confirmPrice(e, item) {
		//console.log('onSelect --- ', item)
	  // console.log('e --- ', e, item)
	   let info = item.PriceList[e.detail.value]
	 	//console.log('onSelect --- ', JSON.stringify(result))
	  item.ProUnitName = info.fUnit
	  item.fSallPrice = info.fPrice
	  this.$forceUpdate()
	},
    currentChange(e) {
      this.current = e
    },
    personSelect() {
      uni.navigateTo({
        url: './personnellist'
      })
      this.action = -1
    },
    //删除
    delsdit(index) {
      // if (this.formdata.length > 1) {
      // console.log(1)
      this.formdata.splice(index, 1)
      // }
    },
    pzshow() {
      // 查看凭证图片\
      var p = []
      for (let i in this.simgs) {
        p.push(this.simgs[i].path)
      }
      this.$api.previewImgs(p, this.simgs[0].path)
      this.action = -1
    },
    Submit() {
		if (!this.clineOnce) return false
		this.clineOnce = false
      // uni.navigateTo({
      // 	url:"./sale_confirmorder"
      // })
      // order/addOrder 添加进货订单
      let txt
     
	 // if (this.userLi.length == 0) {
     //   txt = '请选择销售人员'
     // }
	  
     // if (this.simgs.length == 0) {
     //   txt = '请上传订单凭证'
     // }
      if (this.formdata.length == 0) {
        txt = '请添加进货产品'
      }
      if (txt) {
        uni.showToast({
          title: txt,
          icon: 'none'
        })
        return
      }
	  this.formdata.forEach(x => (x.total = (x.fCount * x.fSallPrice) - (x.fRetCount * x.fSallPrice),
	  x.fType=x.fType+1))
	  let info = this.formdata.map(x => ({ fOrderId: 0, fMrkId: this.form.MrkId, fMrkName: this.form.MrkName, fProId: x.fId, fProName: x.fTitle,fUnit:x.ProUnitName, fPrice: x.fSallPrice, fPriceType: this.current, fCount: x.fCount,fCoverCount: x.fCoverCount,fGiveCount: x.fGiveCount,fExcCount: x.fExcCount,fRetCount: x.fRetCount, fMoney: x.total, fType: x.fType, fOverTime: x.fExTime, fInfo: x.fInfo, fBuyType: 0 }))
	    this.form.prolist=info
    //  this.form.Pic = this.simgs.map(x => x.sFileUrl).toString()
       this.form.fMoney = this.total
      this.$axios('api/OrderBasic/AddDetail', 'post', { value: this.form }).then(res => {
	  if(res.Success)
	  {  
        this.addUserDetail(res.Value)
      //  this.addOrderDetail(res.Value)
	
		 
       // this.$api.handleBack('添加订单成功')
        this.userLi = []
        this.simgs = []
        this.formdata = []
        getApp().globalData.addCusGoodLi = []
        getApp().globalData.selectUserli = []
        getApp().globalData.sureSelectImg = []
		
	   this.$api.switchTabToUrl('提交成功', '/pages/order/order')
			 
	  }
	  else
	  {
			uni.showToast({
			  title: '提交失败：'+ res.Message,
			  duration: 1000,
			  icon: 'none'
			})
			
		  this.clineOnce = true
	  }
      })
    },
    addOrderDetail(id) {
      this.formdata.forEach(x => (x.total = x.fCount * x.fSallPrice))
      let info = this.formdata.map(x => ({ fOrderId: id, fMrkId: this.form.MrkId, fMrkName: this.form.MrkName, fProId: x.fId, fProName: x.fTitle, fPrice: x.fSallPrice, fPriceType: this.current, fCount: x.fCount,fCoverCount: x.fCoverCount,fGiveCount: x.fGiveCount,fExcCount: x.fExcCount, fMoney: x.total, fType: 0, fOverTime: x.fExTime, fInfo: x.fInfo, fBuyType: 0 }))
      this.$axios('api/OrderPro/AddDetail', 'post', { value: info }).then(res => {})
    },
    addUserDetail(id) {
		 if (this.userLi.length == 0)
		 {
			 this.$axios('api/OrderUser/AddMyDetail', 'post', { value: id }).then(res => {})
		 }
		 else
		 {
			 let info = this.userLi.map(x => ({ OrderId: id, UserId: x.fId, UserName: x.fName }))
			 this.$axios('api/OrderUser/AddDetail', 'post', { value: info }).then(res => {})
		 }

    },
    getClist() {
      // this.$axios('api/OrderPro/AddDetail', 'post', {})
    },
    selectGood() {
      // this.action = e;
      uni.navigateTo({
        url: '/pages/sale/draw/drawSelect?fId=' + this.form.VisitId
      })
      getApp().globalData.addCusGoodLi = this.formdata
    },
    add_ontime() {
      var e = this.formdata.length + 1
      var v = {
        gid: '',
        gname: '',
        remarks: '',
        num: '',
        maxnum: 0,
        price: '',
        sall_price: ''
      }
      this.formdata.unshift(v)
    },
    imgshow() {
      uni.navigateTo({
        url: './ordervoucher'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-footer {
  text-align: center;
  position: sticky;
  bottom: 2%;
  margin-top: 30rpx;
  u-button {
    display: inline-block;
  }
  u-button + u-button {
    margin-left: 50rpx;
  }
}
u-table,
.u-table {
  margin: 30rpx 0;
}
.topheader {
  padding: 0 32upx;
  border-bottom: 1px solid rgba(0, 0, 0, 0.09);
}

.titel {
  color: #34404a;
  font-size: 32upx;
  padding: 32upx 0;
}

.img60 {
  width: 60upx;
  height: 60upx;
  border-radius: 30upx;
}

.img60:nth-child(1) {
  transform: translateX(60upx);
}

.img60:nth-child(2) {
  transform: translateX(30upx);
}

.imgadd {
  width: 26upx;
  height: 26upx;
  display: block;
}

.bu_text {
  color: #2b88fe;
  font-size: 28upx;
  padding-left: 10upx;
}

.addBtn {
  color: #999;
}

.nametext {
  color: #666;
  font-size: 24upx;
  line-height: 80upx;
  background: #f8f8f8;
  padding: 0 20rpx;
  margin: 0 -20rpx;
}

.listshow {
  padding: 0 32upx;
  line-height: 112upx;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.leftyext {
  width: 150upx;
  color: #333;
  font-size: 28upx;
}

.butbox {
  position: sticky;
  bottom: 20upx;
  left: 10%;
  width: 80%;
  height: 85upx;
  background: #007aff;
  border-radius: 10upx;
  text-align: center;
  color: #fff;
  font-size: 32upx;
  line-height: 85upx;
  z-index: 9;
}
.app-product {
  min-height: 100vh;
  background-color: #fff;
}
.product-list {
  padding: 30rpx;
}
</style>
